package tony.test.mybatis.datascope

import com.baomidou.mybatisplus.annotation.DbType
import com.baomidou.mybatisplus.core.metadata.IPage
import org.apache.ibatis.executor.Executor
import org.apache.ibatis.mapping.BoundSql
import org.apache.ibatis.mapping.MappedStatement
import org.apache.ibatis.session.ResultHandler
import org.apache.ibatis.session.RowBounds
import tony.core.utils.getLogger
import tony.mybatis.interceptor.PaginationInnerInterceptor

/**
 * 自定义分页拦截器，用于捕获最终生成的SQL
 */
class TestPaginationInterceptor(dbType: DbType) : PaginationInnerInterceptor(dbType) {

    private val capturedSqls = mutableListOf<String>()
    private val capturedCountSqls = mutableListOf<String>()

    override fun beforeQuery(
            executor: Executor,
            ms: MappedStatement,
            parameter: Any,
            rowBounds: RowBounds,
            resultHandler: ResultHandler<*>,
            boundSql: BoundSql
    ) {
        // 先调用父类方法处理分页
        super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql)

        // 捕获最终生成的SQL
        val finalSql = boundSql.sql
        capturedSqls.add(finalSql)
        getLogger().info("=== Captured final SQL after pagination: $finalSql")
    }

    override fun autoCountSql(page: IPage<*>, sql: String): String {
        val countSql = super.autoCountSql(page, sql)
        capturedCountSqls.add(countSql)
        getLogger().info("=== Captured count SQL: $countSql")
        return countSql
    }

    fun clearCapturedSqls() {
        capturedSqls.clear()
        capturedCountSqls.clear()
    }

    fun getLastCapturedSql(): String? = capturedSqls.lastOrNull()
    fun getLastCapturedCountSql(): String? = capturedCountSqls.lastOrNull()
}
